package com.sen.common.widget.form;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.sen.common.widget.Component;

/**
 * @author sen
 */
public class Select extends Component {

	private String selectedOption;

	public Select() {
		this(null);
	}

	public Select(String name) {
		this(null, name);
	}

	public Select(String id, String name) {
		super("select");
		this.id(id).name(name);
	}

	public Select option(String value, String text) {
		return option(new SelectOption(value, text));
	}
	
	public Select option(SelectOption option) {
		this.add(option);
		return this;
	}

	public Select clearOptions() {
		super.clearChildren();
		return this;
	}

	public Select emptyOption() {
		return emptyOption("");
	}

	public Select emptyOption(String emptyOption) {
		this.add(new SelectOption("", StringUtils.defaultString(emptyOption, "")));
		return this;
	}

	public Select selected(String selected) {
		this.selectedOption = selected;
		return this;
	}

	@Override
	public String toHtml() {
		makeSelectedOption();
		return super.toHtml();
	}

	private void makeSelectedOption() {
		if (null == selectedOption) {
			return;
		}
		List<Component> options = getChildren();
		for (Component component : options) {
			SelectOption option = (SelectOption) component;
			if (selectedOption.equals(option.getValue())) {
				option.selected();
				break;
			}
		}
	}
}
